#!/usr/bin/env python3
#-*- coding: utf-8 -*-

__auther__ = 'teffy'

'''
@filename dbutil
@created on 2017-12-18
@poject:work-kit
@auther:teffy
'''

import sqlite3
from settings import Settings
from sqlalchemy import *

def singleton(cls,*args,**kw):
    instances = {}
    def _singleton():
        if cls not in instances:
            instances[cls] = cls(*args,**kw)
        return instances[cls]
    return _singleton


@singleton
class DBUtil(object):

    def __init__(self):
        self.settings = Settings()
        self.conn = None
        self.cursor = None
        self.open()

        db = create_engine('sqlite://'+self.settings.db_file)
        metadata = BoundMetaData(db)


    def open(self):
        try:
            self.conn = sqlite3.connect(self.settings.db_file)
            self.cursor = self.conn.cursor()
            self.cursor.execute('CREATE TABLE IF NOT EXISTS commands (id INT PRIMARY KEY NOT NULL ,parent_id INT,command varchar(50),params varchar(100))')
        except sqlite3.Error as e:
            print("connect db failed")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def close(self):
        if self.conn:
            self.conn.commit()
            self.cursor.close()
            self.conn.close()

    def insert(self,id,parent_id,command,param):
        if self.conn:
            self.cursor.execute('INSERT INTO commands VALUES (1,0,"adb","devices")')

